import React, { useState, useEffect } from 'react';
import { TjForm } from '@/tjComponents';
import { Button, Form, Select } from 'antd';
import _ from 'lodash';
import { HttpCode } from '#/utils/contacts.js';
import type { Store } from 'antd/lib/form/interface';
import type { ProvinceType, StationType } from '@/hooks/useRequestPowerAfterInit';
import { getSchedulingNameList } from '../../service';
import './index.less';

const { Option } = Select;

const DrawerContent: React.FC<IDrawerContentProps> = (props) => {
  const [form] = Form.useForm();
  const [stationList, setStationList] = useState<StationType[]>([]);
  const [schedulingList, setSchedulingList] = useState<any[]>([]);

  const onValuesChange = (changedValues: any, value: any) => {
    const cleanedData = _.omitBy(value, (v: any) => _.isNil(v) || v === '');

    if (cleanedData && Object.keys(cleanedData).length > 0) {
      props.isEdit(true);
    } else {
      props.isEdit(false);
    }
  };

  const submit = () => {
    form.validateFields().then((res) => {
      const newData = {
        marketId: props.marketId || '',
        ...res,
      };
      if (props.values && Object.keys(props.values).length > 0) {
        newData.id = props.values.id;
      }
      props.submit({ ...newData });
    });
  };

  const changeStationId = (val: string) => {
    setSchedulingList([]);
    querySchedulingNameList([val]);
    form.setFieldsValue({
      schedulingName: undefined,
    });
  };

  const querySchedulingNameList = (ids: string[]) => {
    getSchedulingNameList(ids).then((res: any) => {
      if (res && res.statusCode === HttpCode.SUCCESS) {
        setSchedulingList(res.data);
      }
    });
  };

  useEffect(() => {
    const marketId = _.get(props, 'marketId', 'PHBSX');
    if (marketId && props.optionsData) {
      if (props.optionsData.province && props.optionsData.province.length > 0) {
        const item: ProvinceType | undefined = props.optionsData.province.find(
          (item: ProvinceType) => item.value === marketId,
        );
        if (item) {
          setStationList(item.stations);
        }
      }
    }
  }, [props.marketId]);

  return (
    <div className="drawer-content">
      <div className="title">基本信息</div>
      <div className="form-box">
        <TjForm
          useGrid={{
            row: {
              gutter: 40,
            },
            col: {
              span: 8,
            },
          }}
          layout="vertical"
          onValuesChange={onValuesChange}
          items={[
            {
              name: 'stationId',
              label: '交易单元',
              rules: [{ required: true, message: '请选择交易单元' }],
              render: (
                <Select
                  disabled={stationList.length === 0 || props.values}
                  onChange={changeStationId}
                >
                  {stationList.map((v) => {
                    return (
                      <Option value={v.stationId} key={v.stationId}>
                        {v.stationName}
                      </Option>
                    );
                  })}
                </Select>
              ),
            },
            {
              name: 'schedulingName',
              label: '场站名称',
              rules: [{ required: true, message: '请选择场站名称' }],
              render: (
                <Select
                  options={schedulingList}
                  disabled={schedulingList.length === 0 || props.values}
                />
              ),
            },
            {
              name: 'userName',
              label: '账号名称',
              rules: [
                { required: true, message: '请输入账号名称' },
                { max: 50, message: '请输入不超过50个字符' },
              ],
            },
            {
              name: 'password',
              label: '账号密码',
              rules: [
                { required: true, message: '请输入账号密码' },
                // {
                //   pattern: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&#~-])[A-Za-z\d@$!%*?&#~-]{8,}$/,
                //   message: '密码长度必须为8位，切需包含数字、字母、特殊字符',
                // },
                { max: 30, message: '请输入不超过30个字符' },
              ],
            },
          ]}
          form={form}
        />
      </div>
      <div className="btn">
        <Button
          style={{ width: 98, height: 32 }}
          type="primary"
          onClick={submit}
          loading={props.loading}
        >
          提交
        </Button>
      </div>
    </div>
  );
};

interface IDrawerContentProps {
  loading: boolean;
  values: any;
  optionsData: {
    province: ProvinceType[];
  };
  submit: (value: Store) => void;
  isEdit: (flag: boolean) => void;
  marketId?: string;
}

export default DrawerContent;
